package com.springstudy.listener;


import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author Tamako
 * @since 2025/1/13 14:26
 */
public class ContextLoaderListener implements ServletContextListener {
    private static final String CONTEXT_CONFIG_LOCATION = "contextConfigLocation";

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("ContextLoaderListener init ...");
        ServletContext servletContext = sce.getServletContext();
        //0.获取全局参数
        String contextConfigLocation = servletContext.getInitParameter(CONTEXT_CONFIG_LOCATION);
        //解析出配置文件名称
        contextConfigLocation = contextConfigLocation.substring("classpath:".length());
        //1.创建spring容器
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(contextConfigLocation);
        //2.将容器存储到ServletContext中
        servletContext.setAttribute("applicationContext", context);

    }
}
